package com.warthur.vertx.demo.handler;

import com.warthur.vertx.demo.common.Constants;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.stream.Collectors;

/**
 * @author warthur
 * @date 2019/10/10
 */
@Slf4j
public class WebLogHandler {

    private static final CharSequence HEADER_NAME = HttpHeaders.createOptimized("x-response-time");

    /**
     * 日志记录
     * @param context 路由上下文
     */
    public static void handle(RoutingContext context) {

        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();

        StringBuilder requestInfo = new StringBuilder(Constants.LF)
                .append("请求：").append(request.rawMethod()).append(Constants.BS).append(request.absoluteURI())
                .append(Constants.LF).append(Constants.LF);

        // 请求头
        if (!request.headers().isEmpty()) {
            String headers = request.headers().entries().stream().map(entry -> entry.getKey() + ": " + entry.getValue())
                    .collect(Collectors.joining(Constants.LF));
            requestInfo.append(headers).append(Constants.LF).append(Constants.LF);
        }

        // 请求体
        if (context.getBody() != null && context.getBody().length() > 0) {
            requestInfo.append(context.getBodyAsString()).append(Constants.LF).append(Constants.LF);
        }

        // 响应结束事件
        response.bodyEndHandler((v) -> {

            requestInfo.append("响应：").append(response.getStatusCode()).append(Constants.BS).append(response.getStatusMessage())
                    .append(Constants.LF).append(Constants.LF);

            if (!response.headers().isEmpty()) {
                String headers = response.headers().entries().stream().map(entry -> entry.getKey() + ": " + entry.getValue())
                        .collect(Collectors.joining(Constants.LF));
                requestInfo.append(headers).append(Constants.LF);
            }

            String res = context.get("response");
            if (StringUtils.isNotEmpty(res)) {
                requestInfo.append(Constants.LF).append(res).append(Constants.LF);
            }
            log.info(requestInfo.toString());
        });

        context.next();
    }
}
